# -*- coding: utf-8 -*-

import itchat
import requests
import time
import pymysql


class app:
    def __init__(self):
        #组name
        self.chatUserName = ''
        #mysql实例
        self.db = None
        self.cursor = None

    """
       主程序运行
    """
    def run(self):
        # itchat.run()
        itchat.auto_login(hotReload=True)
        # itchat.auto_login()
        # 传入update键为True将可以更新群聊列表并返回通讯录中保存的群聊列表
        itchat.get_chatrooms(update=True)
        chatrooms = itchat.search_chatrooms('币提醒小助手')
        chatUserName = chatrooms[0]['UserName']
        self.chatUserName = chatUserName
        while (True):
            #数据库开启
            self.db = pymysql.connect("localhost", "root", "wei@7713", "bitixing", charset='utf8')
            self.cursor = self.db.cursor()
            #推送
            self.push_exchange()
            self.push_news()
            #数据库关闭
            self.cursor.close()
            self.db.close()
            #三秒后继续
            time.sleep(10)

    def push_news(self):
        # 推送资讯消息
        news_news = "select `id`,`service_name`,`title`,`content`,`create_at` from coin_news where status = 0  limit 1"
        self.cursor.execute(news_news)
        news_data = self.cursor.fetchone()
        if news_data != None:
            print('waiting send')
            id = news_data[0]
            msg = "资讯APP名称：" + news_data[1] + '\n'
            msg += "标题: " + news_data[2] + '\n'
            msg += "时间: " + str(news_data[4]) + '\n'
            msg += "正文: " + news_data[3]
            itchat.send(msg, self.chatUserName)
            # 将状态置为1
            sql = "UPDATE `coin_news` SET `status` = '1' WHERE `id` = %s" % (id)
            print(sql)
            try:
                # 执行SQL语句
                self.cursor.execute(sql)
                # 提交到数据库执行
                self.db.commit()
            except:
                print('error')
                # 发生错误时回滚
                self.db.rollback()

    def push_exchange(self):
        # 推送交易所信息
        self.cursor.execute(
            "select `id`,`exchange_title`,`title`,`content`,`create_at`,`url` from coin_Information where status = 0  limit 1")
        data = self.cursor.fetchone()
        if data != None:
            print('waiting send')
            id = data[0]
            msg = "交易所：" + data[1] + '\n'
            msg += "标题: " + data[2] + '\n'
            msg += "正文: " + data[3] + '\n'
            msg += "时间: " + str(data[4]) + '\n'
            msg += "详情: " + data[5]
            itchat.send(msg, self.chatUserName)
            # 将状态置为1
            sql = "UPDATE `coin_Information` SET `status` = '1' WHERE `coin_Information`.`id` = %s" % (id)
            try:
                # 执行SQL语句
                self.cursor.execute(sql)
                # 提交到数据库执行
                self.db.commit()
            except:
                # 发生错误时回滚
                self.db.rollback()
                # 关闭数据库连接





app =  app()
app.run()
